import SprayPath from "../../model/SprayPath.js";
import SprayPathIndicator from "./SprayPathIndicator.js";

// 负责读取 AI 规划出来的航线，并进行格式转换，转换为 SprayPath 类型的数据
export default class SprayPathReader {
  /**
   * 航线路径节点
   * @type {SprayPath[]}
   */
  sprayPaths = []
  sprayRect = {w: 0, h: 0}
  /**
   * @type {MainStore}
   */
  store
  scene

  constructor(store, scene) {
    this.store = store
    this.scene = scene
  }

  /**
   * 根据json文件的url，来加载 AI 规划出来的航线，因为航线中的航点可能很多，上千个航点
   * 数据库对字符串的字段 有长度限制，不能超过2的16次方，65536个字符
   * @param {string} jsonUrl
   */
  loadSprayPathsFromUrl(jsonUrl, toEarthMat) {
    fetch(jsonUrl, {})
      .then(
        (resp) => {
          if (resp.ok) {
            return resp.text();
          } else {
            console.error('没有找到 AI规划出来的航线，', jsonUrl);
            throw new Error(`没有找到 AI规划出来的航线，`);
          }
        },
        (reason) => {
          console.log('loadB3dmsModel, failed: ', reason);
        },
      )
      .then((jsonStr) => {
        this.loadSprayPathsFromAI(jsonStr, toEarthMat);
      });
  }

  loadSprayPathsFromAI(jsonStr, toEarthMat) {
    const obj = JSON.parse(jsonStr);
    const planeDist = obj.plate_distance;
    const penRect = obj.pen_rect; // [0.1, 0.1]
    this.sprayRect.w = penRect[0];
    this.sprayRect.h = penRect[1];
    const taskList = obj.splitTaskList; // [{}, ...]
    this.sprayPaths.length = 0;
    taskList.forEach((taskObj) => {
      const sprayPath = new SprayPath().setPenRect(penRect);
      sprayPath.fromJson(taskObj, planeDist);
      this.sprayPaths.push(sprayPath);
    });
    this._drawPaths();
  }

  clearSprayPathIndicators() {
    this.sprayPaths.length = 0;
    this.store.sprayPathIndicators.forEach((it) => it.removeFromParent());
    this.store.sprayPathIndicators.length = 0;
  }

  _drawPaths() {
    const {w, h} = this.sprayRect
    this.sprayPaths.forEach(sprayPath => {
      const pathIndicator = new SprayPathIndicator(sprayPath, w, h)
      this.scene.add(pathIndicator)
      this.store.sprayPathIndicators.push(pathIndicator)
    })
  }

  /**
   * 显示编辑好的喷涂路线
   * @param {AddSprayPathPointPlugin} pathEdit
   */
  loadSprayPathFromEditPlugin(pathEdit) {
    if (!pathEdit.sprayPath) {
      return;
    }
    const sprayPath = pathEdit.sprayPath;
    const {w, h} = sprayPath.editableRect;
    this.sprayPaths.push(sprayPath);
    this.sprayPaths.forEach(sprayPath => {
      const pathIndicator = new SprayPathIndicator(sprayPath, w, h)
      this.scene.add(pathIndicator)
      this.store.sprayPathIndicators.push(pathIndicator)
    })
  }
}
